import 'package:flutter_admin/models/odoo/sale_bid_project.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_dialog.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_edit.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/lend_or_return.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/utils/utils.dart';

import 'dms_file/dms_file_list.dart';

class UdtTbDocmentstockList extends StatefulWidget {
  UdtTbDocmentstockList({Key? key}) : super(key: key);

  @override
  _UdtTbDocmentstockListState createState() => _UdtTbDocmentstockListState();
}

class _UdtTbDocmentstockListState extends State<UdtTbDocmentstockList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'id', asc: false)]);
  UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock();
  List<UdtTbDocmentstock> selectedList = [];
  //文档类别
  List<SelectOptionVO> docmenttypeList = [];
  //文档状态
  List<SelectOptionVO> statusList = [];
  //部门
  List<SelectOptionVO> departmentList = [];
  UserInfo userInfo = StoreUtil.getCurrentUserInfo();
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      departmentList = await DynamicDataApi.getModelSelect(
          model: "hr.department", name: "complete_name");
    } else {
      docmenttypeList = await DynamicDataApi.getModelSelect(
          active: false,
          model: "dms.documenttype",
          name: "documenttypename",
          key: "department_id",
          val: int.parse(userInfo.deptId!));
    }
    statusList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: '0', label: "入库"),
      SelectOptionVO(value: '1', label: "借出")
    ];
    _query();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
        width: 280,
        label: '所属部门',
        dataList: departmentList,
        value: udtTbDocmentstock.departmentId,
        onSaved: (v) => {udtTbDocmentstock.departmentId = v},
        onChange: (v) async {
          if (udtTbDocmentstock.departmentId != v) {
            formKey.currentState!.save();
            udtTbDocmentstock.departmentId = v;
            udtTbDocmentstock.documenttypeId = null;
            try {
              docmenttypeList = await DynamicDataApi.getModelSelect(
                  active: false,
                  model: "dms.documenttype",
                  name: "documenttypename",
                  key: "department_id",
                  val: int.parse(v));
            } catch (e) {
              docmenttypeList = [];
            }
            setState(() {});
          }
        },
      ): CryInput(
            width: 280,
            label: '所属部门',
            enable: false,
            value: userInfo.deptName,
          ),
          CrySelect(
            width: 280,
            label: '档案项目',
            dataList: docmenttypeList,
            value: udtTbDocmentstock.documenttypeId,
            onSaved: (v) => {udtTbDocmentstock.documenttypeId = v},
          ),
          CryInput(
            width: 140,
            label: '附件名称',
            value: udtTbDocmentstock.fileName,
            onSaved: (v) {
              udtTbDocmentstock.fileName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '档案盒名称',
            value: udtTbDocmentstock.documentname,
            onSaved: (v) {
              udtTbDocmentstock.documentname = v;
            },
          ),
          CrySelect(
            width: 120,
            label: '状态',
            dataList: statusList,
            value: udtTbDocmentstock.status,
            onSaved: (v) {
              udtTbDocmentstock.status = v;
            },
          ),
          CryInput(
            width: 140,
            label: '备注',
            value: udtTbDocmentstock.remark,
            onSaved: (v) {
              udtTbDocmentstock.remark = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('档案盒状态')),
        DataColumn(label: Text('档案盒编号')),
        DataColumn(label: Text('档案盒名称')),
        DataColumn(label: Text('所属部门')),
        DataColumn(label: Text('档案项目')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('存放区域')),
        DataColumn(label: Text('存放位置')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建时间')),
      ],
      getCells: (m) {
        UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock.fromMap(m);
        var flag = udtTbDocmentstock.remark!.contains("\n");
        var remark;
        if (flag) {
          remark = udtTbDocmentstock.remark!.split("\n")[0] + "...";
        } else {
          remark = udtTbDocmentstock.remark;
        }
        return [
          DataCell(Text(udtTbDocmentstock.status != null
              ? udtTbDocmentstock.status == '0'
                  ? '入库'
                  : '借出'
              : '--')),
          DataCell(Text(udtTbDocmentstock.documentno ?? '--')),
          DataCell(Text(udtTbDocmentstock.documentname ?? '--')),
          DataCell(Text(udtTbDocmentstock.departmentName ?? '--')),
          DataCell(Text(udtTbDocmentstock.documenttypeName ?? '--')),
          DataCell(Text(remark),
              onTap: flag ? () => _openDialog(udtTbDocmentstock.remark) : null),
          DataCell(Text(udtTbDocmentstock.areaName ?? '--')),
          DataCell(Text(udtTbDocmentstock.locationName ?? '--')),
          DataCell(Text(udtTbDocmentstock.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(udtTbDocmentstock.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(
            context,
            selectedList.length == 1 && selectedList[0].status == '0'
                ? () => _edit(selectedList[0])
                : null),
        CryButtons.delete(
            context,
            selectedList.length != 0 && selectedList[0].status == '0'
                ? () => _delete(selectedList)
                : null),
        CryButtons.lend(
          context,
          selectedList.length == 1 && selectedList[0].status == '0'
              ? () => _lendOrReturn(selectedList[0])
              : null,
        ),
        CryButtons.retum(
          context,
          selectedList.length == 1 && selectedList[0].status == '1'
              ? () => _lendOrReturn(selectedList[0])
              : null,
        ),
        CryButtons.dmsFile(
          context,
          selectedList.length == 1 ? () => _dmsFile(selectedList[0]) : null,
        ),
        CryButtons.print(
          context,
          selectedList.length != 0 ? () => _print(selectedList) : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              isDisplayDesktop(context) ? buttonBar : Container()
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _openDialog(String? remark) {
    Size size = boundingTextSize(remark!);
    showDialog(
        context: context,
        builder: (BuildContext context) => Dialog(
                child: SizedBox(
              width: size.width,
              height: size.height + 120 < 600 ? size.height + 120 : 600,
              child: Scaffold(
                appBar: AppBar(
                  title: Text("备注详情"),
                ),
                body: SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.all(10),
                    child: Text(remark),
                  ),
                ),
              ),
            ))).then((v) {});
  }

  static Size boundingTextSize(String text,
      {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (text == null || text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        text: TextSpan(text: text),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  _edit(UdtTbDocmentstock? udtTbDocmentstock) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbDocmentstockEdit(
          udtTbDocmentstock: udtTbDocmentstock,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (udtTbDocmentstock == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    udtTbDocmentstock = UdtTbDocmentstock();
    // var deparment =
    //     StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    // udtTbDocmentstock.departmentId = deparment[0].toString();
    // udtTbDocmentstock.departmentName = deparment[1].toString();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await UdtTbDocmentstockOdooApi.filePageSearch(data: {
      "page": page,
      "domainList": udtTbDocmentstock.toDomainList(),
    });

    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<UdtTbDocmentstock> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List domainList = selectedList.map((v) {
        return ['documentno', '=', v.documentno];
      }).toList();
      var result = await UdtTbDocmentstockOdooApi.removeByIds(domainList);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbFocmentstockDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbDocmentstock = v;
        _query();
      }
    });
  }

  _lendOrReturn(UdtTbDocmentstock? udtTbDocmentstock) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: LendOrReturn(
          udtTbDocmentstock: udtTbDocmentstock,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _loadData();
      }
    });
  }

  _dmsFile(UdtTbDocmentstock udtTbDocmentstock) {
    SaleBidProject? saleBidProject;
    Utils.fullscreenDialog(DmsFileList(
        udtTbDocmentstock: udtTbDocmentstock, saleBidProject: saleBidProject));
  }

  _print(List<UdtTbDocmentstock> udtTbDocmentstockList) async {
    String data = "";
    for (var i = 0; i < udtTbDocmentstockList.length; i++) {
      if (i != udtTbDocmentstockList.length - 1) {
        data += udtTbDocmentstockList[i].documentno!;
        data += ";";
        continue;
      }
      data += udtTbDocmentstockList[i].documentno!;
    }
    ResponseBodyApi res = await DynamicDataApi.devicePrint(data: data);
    if (res.success!) {
      CryUtils.message("打印成功");
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<UdtTbDocmentstock>((e) => UdtTbDocmentstock.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          cryConfirm(context, S.of(context).confirmDelete, (context) async {
            _delete(selectedList);
          });
        } else if (v == OperationType.lendOrReturn) {
          _lendOrReturn(selectedList[0]);
        } else if (v == OperationType.dmsFile) {
          _dmsFile(selectedList[0]);
        } else if (v == OperationType.print) {
          _print(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && selectedList[0].status == '0',
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0 && selectedList[0].status == '0',
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.lendOrReturn,
          enabled: selectedList.length == 1 && selectedList[0].status == '0',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && selectedList[0].status == '0',
            title: Text('借阅'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.lendOrReturn,
          enabled: selectedList.length == 1 && selectedList[0].status == '1',
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1 && selectedList[0].status == '1',
            title: Text('归还'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('电子文档'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.print,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.print_rounded),
            enabled: selectedList.length != 0,
            title: Text('打印'),
          ),
        ),
      ],
    );
  }
}
